//
//  KDesaturate.m
//  Kia
//
//  Created by Andrey on 13/05/2009.
//  Copyright 2009 Karma Software. All rights reserved.
//

#import "KDesaturate.h"
#import "KPixel.h"
#import "KImage.h"
#import "KSimpleFloatArray.h"

@implementation KDesaturate

- (KPixel*) processPixel: (KPixel*)pixel ofImage: (KImage*)image atX: (NSUInteger)x y: (NSUInteger)y
{
	KSimpleFloatArray* channelFractions = [parameters objectForKey:@"ChannelFractions"];
	
	CGFloat resultValue = 0.0;
	KRedundantColorVector colorVector = [pixel redundantColorVector];
	for (enum KImageChannel channel = RedImageChannel; channel <= BlueImageChannel; channel++)
	{
		resultValue += colorVector.data[channel] * channelFractions.data[channel];
	}
	if (resultValue > 1.0) resultValue = 1.0;
	
	for (enum KImageChannel channel = RedImageChannel; channel <= BlueImageChannel; channel++)
	{
		[pixel setValue:resultValue forChannel:channel];
	}
	
	return pixel;
}

- (KImage*) processImage: (KImage*)image inPlace: (Boolean)inPlace
{
	ForEachImagePixel(image)
	{
		[self processPixel:[image pixelAtX:x y:y] ofImage:image atX: x y: y];
	}
	
	return image;
}

- (NSString*) name
{
	return @"Desaturate";
}

- (void) dealloc
{
	[super dealloc];
}

@end
